import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * @Author @fiber-cloud
 * @Date 2025/10/8 21:05
 * UDP版本的回显客户端
 */
public class UdpEchoClient {

    private DatagramSocket socket = null;
    private String serverIp = null;
    private int serverPort = 0;

    public UdpEchoClient(String serverIp,int serverPort)throws SocketException{
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }


    public void start()throws IOException{

        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);

        while (true){
            //从控制台读取要发送的内容
            System.out.println("> ");
            String request = scanner.next();
            if (request.equals("exit")){
                System.out.println("goodbye！");
                break;
            }

            //构造一个UDP请求，并将其发送出去
            //构造请求时，要把serverIp和port都传过来，这里的IP地址要填写一个32位整数
            //上述的 IP 地址是一个字符串. 需要使用 InetAddress.getByName 来进行一个转换.
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);//发送给谁，ip和端口
            socket.send(requestPacket);
            //读取服务器的UDP响应，并对其解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());

            System.out.println(response);

        }
    }


    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);

        client.start();
    }
}
